import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPClient {

    private DatagramSocket socket = null;
    private final String serverIP;
    private final int serverPort;
    // 客户端启动时,需要知道服务器的ip和端口号
    public UDPClient(String serverIP,int serverPort) throws SocketException {
        // 客户端不需要显示关联端口,系统自动分配空闲端口
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }


    public void start() throws IOException {
        // 希望通过客户端和服务器进行多次交互
        while(true) {
            Scanner scanner = new Scanner(System.in);
            // 1 从控制台读取字符串
            System.out.print("->");
            String request = scanner.next();
            // 2 将字符串构成packet,并发送

            DatagramPacket requestPacket =
                    new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIP)/* 服务器IP*/,
                    serverPort/* 服务器端口 */);
            socket.send(requestPacket);
            // 3 读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            // 4 将响应转换为String
            String response = new String(responsePacket.getData(),
                    0,responsePacket.getLength());
            System.out.printf("req %s resp %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClient udpClient = new UDPClient("127.0.0.1",9090);
        udpClient.start();
    }

}
